import { catchFn } from '@/libs/common'
import { checkOrder } from './api'
import { report } from '@/libs/request'

/**
 * 支付函数模板
 * @param _options 参数
 */
let payFn: (options: any) => Promise<any> = (_options: any) => Promise.reject('暂不支持支付')

// #ifdef MP-WEIXIN
import { pay_mp_weixin } from './pay-mp-weixin'
import { updateUserInfo } from '@/libs/user'
import { topMessage } from '@/components/TopMessage/data'
import { update } from './recharge/data'

export * from './pay-mp-weixin'

payFn = async (options: any) => pay_mp_weixin(options)
// #endif

/**
 * 支付
 * @param options 参数
 */
const pay = (options: {
  /** 商品ID */
  itemId: number
  /** 需要解锁的测试分类 */
  testType?: string
  /** 需要解锁的测试结果ID */
  testResultId?: number
}) =>
  catchFn(async () => {
    const order_id = await payFn(options)

    report('pay', {
      order_id,
      item_id: options.itemId,
    })

    if (!order_id) return

    const res = await catchFn(async () => {
      await checkOrder(order_id)
      updateUserInfo()
      update()

      topMessage.success('支付成功')

      return true
    })

    report('pay_result', {
      order_id,
      result: res ? 1 : 0,
    })

    return !!res
  })

export { pay }
